package com.yupi.soulba.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.soulba.model.domain.User;
import com.yupi.soulba.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 黄云杰、过江辉
 * 缓存预热
 */
@Component
@Slf4j
public class PreCacheJob {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    
    @Resource
    private RedissonClient redissonClient;
    
    // 重点用户
    private List<Long> mainUserList = Arrays.asList(5L);
    
    //每天执行一次，预热主页推荐用户 
    @Scheduled(cron = "0 1 22 * * ? ")
    public void doCacheRecommendUser() {
        RLock lock = redissonClient.getLock("soulBa:preCacheJob:doCache:lock");
        try {
            //只有一个线程能获取到锁
            if(lock.tryLock(0, -1, TimeUnit.MILLISECONDS)){
                System.out.println("getLock: " + Thread.currentThread().getId());
                for (Long userId : mainUserList) {
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    Page<User> userPageList = userService.page(new Page<>(1, 20),queryWrapper);
                    String redisKey = String.format("soulBa:user:recommend:%s", userId);
                    ValueOperations<String, Object> redisValueOperations = redisTemplate.opsForValue();
                    try {
                        redisValueOperations.set(redisKey, userPageList, 1, TimeUnit.DAYS);
                    } catch (Exception e) {
                        log.error("redis set key error", e);
                    }
                }
            }
        } catch (InterruptedException e) {
            log.error("doCacheRecommendUser error", e);
        } finally {
            /**
             * 这段代码一定要放进 finally ！！！
             */
            // 只能释放自己的锁
            if(lock.isHeldByCurrentThread()){
                System.out.println("unlock: " + Thread.currentThread().getId());
                lock.unlock();
            }
        }
    }
}
